require 'will_paginate'
class OrgansController < ApplicationController

  def initialize
    @pais = Organ.find :all
    @tiposorgaos = Organtype.find :all
    @campus = Campu.find :all

  end

  def consulta

    @nome = params[:nome]
    @sigla = params[:sigla]


    if !@nome.blank? and @sigla.blank?
      @organs = Organ.paginate :page => params[:page],
        :conditions => ['nome like ?', "%#{@nome}%"],
        :order => 'nome DESC'
    elsif !@nome.blank? and !@sigla.blank?
      @organs = Organ.paginate :page => params[:page],
        :conditions => ['nome like ? and sigla like ?' , "%#{@nome}%","#{@sigla}"],
        :order => 'nome DESC'
    elsif @nome.blank? and !@sigla.blank?
      @organs = Organ.paginate :page => params[:page],
        :conditions => ['sigla = ?',@sigla],
        :order => 'nome DESC'
    elsif @nome.blank? and @sigla.blank?
      @organs = Organ.paginate :page => params[:page],
        :order => 'nome DESC', :per_page => 8
    end



    render :action => :index

  end


  def index
    @organs  = Organ.paginate :page => params[:page], :order => 'nome DESC', :per_page => 8

    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @organs }
    end
  end


  def show
    @organ = Organ.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @organ }
    end
  end


  def new
    @organ = Organ.new

    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @organ }
    end
  end


  def edit
    @organ = Organ.find(params[:id])
  end


  def create
    @organ = Organ.new(params[:organ])

    @organ = modifica @organ,params[:organ]

    respond_to do |format|
      if @organ.save
        flash[:notice] = 'Orgao was successfully created.'
        format.html { redirect_to(organs_url) }
        format.xml  { render :xml => @organ, :status => :created, :location => @organ }
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @organ.errors, :status => :unprocessable_entity }
      end
    end
  end


  def update
    @organ = Organ.find(params[:id])

    respond_to do |format|
      if @organ.update_attributes(params[:organ])
        flash[:notice] = 'Orgao was successfully updated.'
        format.html { redirect_to(organs_url) }
        format.xml  { head :ok }
      else
        format.html { render :action => "edit" }
        format.xml  { render :xml => @organ.errors, :status => :unprocessable_entity }
      end
    end
  end


  def destroy
    @organ = Organ.find(params[:id])
    @organ.destroy

    respond_to do |format|
      format.html { redirect_to(organs_url) }
      format.xml  { head :ok }
    end
  end
end
